<?php
/*
 * @ https://EasyToYou.eu - IonCube v11 Decoder Online
 * @ PHP 7.2 & 7.3
 * @ Decoder version: 1.1.6
 * @ Release: 10/08/2022
 */

// Decoded file for php version 71.
namespace app;

use app\massage\model\Coach;
use app\massage\model\Config;
use app\massage\model\PayConfig;
use app\store\model\StoreList;
use think\App;
use think\facade\Db;

abstract class ApiRest extends BaseController
{
    public $_app;
    public $_controller;
    public $_action;
    public $_method = "GET";
    public $_header = [];
    public $_token;
    public $_lang = "zh-cn";
    public $_role = "guest";
    public $_host;
    public $_ip;
    public $_user;
    public $_user_id;
    public $_uniacid = 666;
    public $is_app = 0;
    protected $middleware = ["app\\middleware\\AppInit"];
    protected $autograph = "";
    protected $uniacid = 0;
    protected $defaultImage = ["avatar" => "https://lbqnyv2.migugu.com/defaultAvatar.png", "image" => "https://lbqnyv2.migugu.com/lbCardDefaultImage.png"];
    protected $check_url = "";
    protected $noNeedLogin = [];

    public function __construct(App $app)
    {
        parent::__construct($app);
        if (in_array($this->_method, ['options', 'Options', 'OPTIONS'])) {
            echo true;
            exit;
        }
        //
        //获取头部信息
        $this->_header = $this->request->header();
        $this->_action = $this->request->action();
        $this->_controller = $this->request->controller();
        $this->_uniacid = !empty($this->_param['i']) ? $this->_param['i'] : 666;
        $this->is_app = isset($this->_header['isapp']) ? $this->_header['isapp'] : 2;
        $this->shareChangeDatas($this->_param);
        if (isset($this->_header['autograph'])) {
            $this->autograph = $this->_header['autograph'];
        }
        //获取配置信息
        $this->_config = longbingGetAppConfig($this->_uniacid);
        //语言
        if (isset($this->_header['lang'])) $this->_token = $this->_header['lang'];
        if (isset($this->autograph)) {
            $this->_user_id = $this->getUserId();
            $this->_user = $this->getUserInfo();
            if (!empty($this->_user)) {
                setCache($this->autograph, $this->_user, 86400 * 3, 999999999999);
            }
            if ($this->checkCoachAccountRoute() == false) {
                $this->errorMsg('need login', 401);
            }
            if (!empty($this->_user['openid'])) {
                $this->checkOrderPayV2($this->_user['openid'], $this->payConfig($this->_uniacid), $this->_uniacid);
            }
        }
    }

    public function shareChangeDatas($input)
    {
//        return true;
        $arr = ["massage/app/Index/configInfo", "shop/app/Index/configInfo", "massage/app/Index/index", "massage/app/Index/serviceList", "massage/app/Index/couponList", "massage/app/Index/getMapInfo", "massage/app/Index/serviceCoachList", "massage/app/Index/typeServiceCoachList", "massage/app/Index/getCity", "massage/app/Index/coachServiceList", "massage/app/IndexUser/index", "massage/app/IndexUser/channelCateSelect", "massage/app/Index/recommendList", "massage/app/IndexOrder/adapayOrderInfo", "massage/app/IndexBalance/cardList", "massage/app/IndexArticle/articleInfo", "massage/app/Index/serviceInfo", "massage/app/Index/serviceCateList", "massage/app/Index/coachInfo", "massage/app/Index/commentList", "massage/app/Index/plugAuth", "massage/app/Index/nearbyLocation", "massage/app/Index/industryServiceList", "massage/app/Index/getServiceObjList", "massage/app/Index/industryGetCoachService", "massage/app/Index/expectationCityCheck", "massage/app/Index/cityData", "massage/app/Index/getCityList", "dynamic/app/IndexDynamicList/dynamicList", "dynamic/app/IndexDynamicList/getFollowData", "store/app/IndexStore/storeList", "store/app/IndexStore/storeInfo", "store/app/IndexStore/storeServiceList", "store/app/IndexStore/commentList", "massage/app/Index/getCoachService", "massage/app/IndexUser/getUserCoachStatus", "massage/app/IndexUser/getWecomStaff", "massage/app/IndexUser/getAddressByIp", "massage/app/IndexUser/addScanRecord", "massage/app/IndexGoods/goodsInfo", "map/app/Index/coachList", "massage/app/Index/agentInfo", "store/app/IndexStore/storeCateList", "massage/app/IndexUser/industryTypeSelect"];
        if (!empty($input["urls"]) && in_array($input["urls"], $arr)) {
            $input["urls"] = trim(strrchr($input["urls"], "/"), "/");
            $this->noNeedLogin[] = $input["urls"];
        }
        return true;
    }

    protected function getUserId()
    {
        // $value = !empty(getCache($this->autograph,999999999999))?getCache($this->autograph,999999999999):getCache($this->autograph,$this->_uniacid);
        $value = $this->getUserInfo();
        if ($value === false && !$this->match($this->noNeedLogin)) {
            $this->errorMsg('need login', 401);
        }
        return !empty($value['id']) ? $value['id'] : 0;
    }

    protected function getUserInfo()
    {
//        $value = !empty(getCache($this->autograph,999999999999))?getCache($this->autograph,999999999999):getCache($this->autograph,$this->_uniacid);
        $value = getCache($this->autograph, 666);
//        var_dump($value);
        if (empty($value) && !$this->match($this->noNeedLogin)) {
            $this->errorMsg('need login', 401);
        }
        if (!empty($value['coach_account_login'])) {
            $coach_model = new Coach();
            $value['id'] = $coach_model->where(['id' => $value['coach_id']])->value('user_id');
        }
        if (!empty($value) && empty($value['coach_account_login'])) {
            $user_model = new \app\massage\model\User();
            $value['balance'] = $user_model->where(['id' => $value['id']])->value('balance');
            $user_status = $user_model->where(['id' => $value['id']])->value('user_status');
            if ($user_status == -1) {
                $this->errorMsg('no auth', 407);
            }
            if ($this->is_app == 1) {
                $value['openid'] = $value['app_openid'];
            } elseif ($this->is_app == 0) {
                $value['openid'] = $value['wechat_openid'];
            } else {
                $value['openid'] = $value['web_openid'];
            }
        }
        return $value;
    }

    public function match($arr)
    {
        $arr = is_array($arr) ? $arr : explode(",", $arr);
        if (!$arr) {
            return false;
        }
        $arr = array_map("strtolower", $arr);
        if (in_array(strtolower($this->request->action()), $arr) || in_array("*", $arr)) {
            return true;
        }
        return false;
    }

    public function checkCoachAccountRoute()
    {
        if (empty($this->_user["coach_account_login"])) {
            return true;
        }
        $url = app("http")->getName() . "/app/" . $this->_controller . "/" . $this->_action;
        $pass_url = ["massage/app/IndexUser/coachInfo", "massage/app/IndexUser/bindAlipayNumber", "massage/app/IndexUser/getAddressByIp", "massage/app/Index/expectationCityCheck", "massage/app/IndexUser/getStoreSelect", "massage/app/IndexUser/industryTypeSelect", "massage/app/IndexUser/stationIconSelect", "massage/app/IndexUser/coachIconSelect", "massage/app/Index/adminCarCashInfo", "massage/app/IndexUser/coachTypeSelect", "massage/app/IndexUser/industryTypeSelect", "massage/app/IndexGoods/goodsInfo", "massage/app/IndexUser/getWecomStaff"];
        if (in_array($url, $pass_url)) {
            return true;
        }
        if (in_array($this->_controller, ["IndexCoach", "IndexDynamicCoach", "Index", "Wx", "WxFile", "IndexMember"])) {
            return true;
        }
        return false;
    }

    public function checkOrderPayV2($openid, $paymentApp, $uniacid)
    {
        $list = pullCache($openid . "payresult", $uniacid);
        $adapay_model = new \longbingcore\wxcore\Adapay($uniacid);
        if (!empty($list)) {
            foreach ($list as $value) {
                if (!isset($value["type"])) {
                    return true;
                }
                if ($value["type"] == "Massage") {
                    $order_model = new massage\model\Order();
                } elseif ($value["type"] == "MassageUp") {
                    $order_model = new massage\model\UpOrderList();
                } elseif ($value["type"] == "Balance") {
                    $order_model = new massage\model\BalanceOrder();
                } elseif ($value["type"] == "ResellerPay") {
                    $order_model = new payreseller\model\Order();
                } elseif ($value["type"] == "AgentRecharge") {
                    $order_model = new mobilenode\model\RechargeList();
                } elseif ($value["type"] == "Memberdiscount") {
                    $order_model = new memberdiscount\model\OrderList();
                } elseif ($value["type"] == "Balancediscount") {
                    $order_model = new balancediscount\model\OrderList();
                }
                if (!isset($order_model)) {
                    return true;
                }
                if ($value["pay_model"] == "weixin") {
                    $wxpay = new shop\controller\IndexWxPay($this->app);
                    $result = $wxpay->checkOrder($value["order_code"], $paymentApp);
                    if (!empty($result["result_code"]) && $result["result_code"] == "SUCCESS" && !empty($result["return_code"]) && $result["return_code"] == "SUCCESS" && !empty($result["trade_state"]) && $result["trade_state"] == "SUCCESS") {
                        $order_model->orderResult($result["out_trade_no"], $result["transaction_id"]);
                    }
                } elseif ($value["pay_model"] == "adapay") {
                    $result = $adapay_model->orderInfo($value["order_code"]);
                    if (isset($result["status"]) && $result["status"] == "succeeded" && !empty($result["id"])) {
                        $pay_record_model = new adapay\model\PayRecord();
                        $dis = ["adapay_id" => $result["id"], "type" => $value["type"]];
                        $record = $pay_record_model->dataInfo($dis);
                        $pay_record_model->dataUpdate($dis, ["status" => 1]);
                        if (!empty($record)) {
                            $order_model->orderResult($record["order_code"], $result["id"]);
                        }
                    }
                }
                return true;
            }
        }
        return true;
    }

    public function payConfig($uniacid = '666', $is_app = 7)
    {
        if ($is_app == 7) {
            $is_app = $this->is_app;
        }
        $uniacid_id = !empty($uniacid) ? $uniacid : $this->_uniacid;
        $pay_model = new PayConfig();
        $config_model = new Config();
        $pay = $pay_model->dataInfo(['uniacid' => $uniacid_id]);
        $config = $config_model->dataInfo(['uniacid' => $uniacid_id]);
        if (empty($pay['mch_id']) || empty($pay['pay_key'])) {
            $this->errorMsg('未配置支付信息' . $uniacid_id);
        }
        $setting['payment'] = [
            'merchant_id' => $pay['mch_id'],
            'key' => $pay['pay_key'],
            'cert_path' => $pay['cert_path'],
            'key_path' => $pay['key_path'],
            'ali_appid' => $pay['ali_appid'],
            'ali_privatekey' => $pay['ali_privatekey'],
            'ali_publickey' => $pay['ali_publickey'],
            'appCretPublicKey' => $pay['appCretPublicKey'],
            'alipayCretPublicKey' => $pay['alipayCretPublicKey'],
            'alipayRootCret' => $pay['alipayRootCret'],
            'alipay_type' => $pay['alipay_type'],
        ];
        $setting['company_pay'] = $config['company_pay'];
        if ($is_app == 0) {
            $setting['app_id'] = $config['appid'];
            $setting['secret'] = $config['appsecret'];
        } elseif ($is_app == 1) {
            $setting['app_id'] = $config['app_app_id'];
            $setting['secret'] = $config['app_app_secret'];
        } else {
            $setting['app_id'] = $config['web_app_id'];
            $setting['secret'] = $config['web_app_secret'];
        }
        $setting['is_app'] = $is_app;
        return $setting;
    }

    public function _empty($method)
    {
        if (method_exists($this, $method . "_" . $this->method . "_" . $this->type)) {
            $fun = $method . "_" . $this->method . "_" . $this->type;
        } elseif ($this->method == $this->restDefaultMethod && method_exists($this, $method . "_" . $this->type)) {
            $fun = $method . "_" . $this->type;
        } elseif ($this->type == $this->restDefaultType && method_exists($this, $method . "_" . $this->method)) {
            $fun = $method . "_" . $this->method;
        }
        if (isset($fun)) {
            return \think\App::invokeMethod([$this, $fun]);
        }
        throw new \Exception("error action :" . $method);
    }

    public function getAuthList()
    {
    }


    /**
     * @Purpose: 通过小程序端的用户标示获取用户id
     *
     * @Author: zzf
     *
     * @Return: mixed 查询返回值（结果集对象）
     */
    //@ioncube.dk myk("sha256", "cnjdbvjdnjd") -> "cff6bcac6bd92467e0cee72e5c879cdbf7044386eda8f464c817bd5c5c963d6f" RANDOM
    public function getLatData($lng, $lat, $uniacid)
    {
        $key = "getCityByLongLatArr" . round($lng, 4) . "-" . round($lat, 4);
        $value = getCache($key, $uniacid);
        if (!empty($value)) {
        }
        $dis = ["uniacid" => $uniacid];
        $config_model = new massage\model\Config();
        $config = $config_model->dataInfo($dis);
        $map_secret = !empty($config["map_secret"]) ? $config["map_secret"] : "bViFglag7C7G7QlZ1MglFyvh40yK1Tir";
        $URL = "https://apis.map.qq.com/ws/geocoder/v1/?location=" . $lat . "," . $lng . "&key=" . $map_secret;
        $data = longbingCurl($URL, []);
        $data = @json_decode($data, true);
        $arr = [];
        if (!empty($data["result"]["address_component"]["city"])) {
            $arr[] = $data["result"]["address_component"]["city"];
        }
        if (!empty($data["result"]["address_component"]["district"])) {
            $arr[] = $data["result"]["address_component"]["district"];
        }
        if (!empty($data["result"]["address_reference"]["town"]["title"]) && $data["result"]["address_reference"]["town"]["title"] == "白沟镇") {
            $arr = str_replace("高碑店市", "保定白沟新城", $arr);
        }
        if (!empty($arr)) {
            setCache($key, $arr, 86400, $uniacid);
        }
        return $arr;
    }


    /**
     * 根据时间获取时间维度
     * @param $start_time
     * @param $end_time
     * @param $coach_id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    //@ioncube.dk myk("sha256", "cnjdbvjdnjd") -> "cff6bcac6bd92467e0cee72e5c879cdbf7044386eda8f464c817bd5c5c963d6f" RANDOM
    protected function getTimeData($start_time, $end_time, $coach_id, $time_, $is_coach = 0, $is_store = 0, $time_long = 0)
    {
        $time_ = (int)$time_;
        $config_model = new Config();
        $store_model = new StoreList();
        $config = $config_model->dataInfo(['uniacid' => $this->_uniacid]);
        $end_time = strtotime($end_time) - strtotime(date("Y-m-d", time())) + strtotime(date("Y-m-d", $time_));
        $start_time = strtotime($start_time) - strtotime(date("Y-m-d", time())) + strtotime(date("Y-m-d", $time_));
        $coach_model = new Coach();
        $coach = $coach_model->dataInfo(['id' => $coach_id]);
        $rest_arr = $coach_model->getCoachRestTime($coach, $start_time, $end_time, $config);
        $end_time = $end_time > $start_time ? $end_time : $end_time + 86400;
        $i = 0;
        $data = [];
        $time = $start_time;
        $time_interval = $is_coach == 1 ? 0 : $config['time_interval'] * 60 - 1;
        $where[] = ['coach_id', '=', $coach_id];
        $where[] = ['end_time', '>=', time()];
        $where[] = ['pay_type', 'not in', [-1, 7]];
        $order = Db::name('massage_service_order_list')->where($where)->field('start_time,end_time,order_end_time,pay_type')->select();
        while ($time < $end_time) {
            $time = $start_time + $config['time_unit'] * $i * 60;
            $times = date("Y-m-d", $time) == date("Y-m-d", $time_) ? $time : $time - 86400;
            if ($time >= $end_time) {
                break;
            }
            if (!empty($data[0]) && $times == $data[0]['time_str']) {
                $i++;
                continue;
            }
            //过期时间直接不显示
            if ($times < time() && $is_coach == 0) {
                $i++;
                continue;
            }
            $max_time = $times + $config['time_unit'] * 60 - 1;
            $max_time = $max_time > $time_long * 60 + $times ? $max_time : $time_long * 60 + $times;
            //时间戳
            $data[$i]['time_str'] = $times;
            $data[$i]['time_text'] = date('H:i', $times);
            $data[$i]['time_texts'] = date('Y-m-d', $times);
            $data[$i]['is_click'] = 0;
            $data[$i]['is_order'] = 0;
            $data[$i]['status'] = 1;
            if (!empty($order)) {
                foreach ($order as $value) {
                    $res = is_time_crossV2($times, $max_time, $value['start_time'] - $time_interval, $value['end_time'] + $time_interval);
                    if ($res == false) {
                        $data[$i]['is_order'] = 1;
                        $data[$i]['status'] = 0;
                    }
                }
            }
            if (!empty($rest_arr) && $data[$i]['status'] == 1) {
                $order_model = new \app\massage\model\Order();
                $res = $order_model->checkCoachRestTime($rest_arr, $times, $max_time);
                if (!empty($res['code'])) {
                    $data[$i]['status'] = 0;
                    $data[$i]['is_click'] = 1;
                }
            }
            if ($times - $time_interval <= time()) {
                $data[$i]['status'] = 0;
            }
            //门店订单 判断门店时间
            if ($is_store == 1 && !empty($coach['store_id'])) {
                $store_status = $store_model->checkStoreStatus($coach['store_id'], $times, $max_time);
                if (!empty($store_status['code'])) {
                    $data[$i]['status'] = 0;
                }
            }
            $i++;
        }
        $data = !empty($data) ? arraySort($data, 'time_str') : $data;
        return $data;
    }

}
